import React,{useState} from "react"

function TodoList(){

    const [tasks,setTasks] = useState([])
    const [newTask,setNewTask] = useState("")

    const addTask = ()=>{
        if(newTask.trim() !== ""){
            setTasks(tasks => [...tasks,newTask])
            setNewTask("")
        }else{
            alert("Task cannot be empty!")
        }

    }

    const deleteTask = (index)=>{
        setTasks((e,i)=>tasks.filter((_,i)=>i!==index))
    }

    const up = (index)=>{
        if(index > 0){
            const updatedTask = [...tasks]
            // swap two elements in an array
            updatedTask[index] = tasks[index-1]
            updatedTask[index-1] = tasks[index]
            // [updatedTask[index],updatedTask[index-1]] = 
            // [updatedTask[index-1],updatedTask[index]]
            setTasks(updatedTask)
        }
    }

    const down = (index)=>{
        if(index < tasks.length-1){
            const updatedTask = [...tasks]
            // swap two elements in an array
            updatedTask[index] = tasks[index+1]
            updatedTask[index+1] = tasks[index]
            // [updatedTask[index],updatedTask[index+1]] = 
            // [updatedTask[index+1],updatedTask[index]]
            setTasks(updatedTask)
        }
    }

    const handleNewTaskChange = (e)=>{
        setNewTask(e.target.value)
    }


    return (
        <div className="to-do-list">
            <h1>To-Do-List</h1>
            
            <div>
                <input
                    type="text"
                    placeholder="Enter new task..."
                    value={newTask}
                    onChange={handleNewTaskChange}
                    />
                <button className="add-button" onClick={addTask}>Add</button>


            </div>

            <ol>
                {
                    tasks.map((task,index)=>{
                        return (
                            <li key={index}>
                                <span className="text">{task}</span>
                                <button className="delete-button" 
                                        onClick={()=>deleteTask(index)}>Remove</button>
                                <button className="move-button" 
                                        onClick={()=>up(index)}>👆</button>
                                <button className="move-button" 
                                        onClick={()=>down(index)}>👇</button>
                            </li>
                        )
                    })
                }
            </ol>

        </div>
    )
}

export default TodoList